<template>
  <div class="app-container">
    <el-tabs v-model="activeTab">
      <!-- 模板管理标签页 -->
      <el-tab-pane label="模板管理" name="template">
        <div class="template-container">
          <div class="template-header">
            <el-button type="primary" @click="handleAddTemplate">新增模板</el-button>
          </div>
          <el-table :data="templateList" style="width: 100%">
            <el-table-column prop="name" label="模板名称" />
            <el-table-column prop="description" label="描述" />
            <el-table-column label="操作" width="280">
              <template #default="scope">
                <el-button type="primary" link @click="handleEditTemplate(scope.row)">编辑</el-button>
                <el-button type="primary" link @click="handleExportTemplate(scope.row)">导出</el-button>
                <el-button type="danger" link @click="handleDeleteTemplate(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
      
      <!-- 代码生成标签页 -->
      <el-tab-pane label="代码生成" name="generation">
        <div class="generation-container">
          <el-form ref="genFormRef" :model="genForm" label-width="120px">
            <el-form-item label="选择模板">
              <el-select v-model="genForm.templateId" placeholder="请选择模板">
                <el-option
                  v-for="item in templateList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <!-- 动态表单项，根据选择的模板动态生成 -->
            <template v-if="genForm.templateId">
              <template v-for="(field, index) in currentTemplate?.variables" :key="index">
                <!-- 普通文本类型 -->
                <el-form-item v-if="field.type === 'text'" :label="field.label">
                  <el-input v-model="genForm.variables[field.key]" :placeholder="'请输入' + field.label" />
                </el-form-item>
                
                <!-- 数组类型 -->
                <template v-else-if="field.type === 'array'">
                  <el-form-item :label="field.label">
                    <div class="array-items-container">
                      <div v-for="(item, itemIndex) in genForm.variables[field.key] || []" :key="itemIndex" class="array-item">
                        <template v-for="arrayField in field.fields" :key="arrayField.key">
                          <div class="field-item">
                            <span class="field-label">{{ arrayField.label }}：</span>
                            <el-input
                              v-model="item[arrayField.key]"
                              :placeholder="'请输入' + arrayField.label"
                              style="width: 200px"
                            />
                          </div>
                        </template>
                        <el-button type="danger" link @click="removeArrayItem(field.key, itemIndex)">删除</el-button>
                      </div>
                      <el-button type="primary" link @click="addArrayItem(field.key, field.fields)">添加{{ field.label }}</el-button>
                    </div>
                  </el-form-item>
                </template>
              </template>
            </template>
            <el-form-item>
              <el-button type="primary" @click="handleGenerate">生成代码</el-button>
            </el-form-item>
          </el-form>
          
          <!-- 生成结果展示 -->
          <div v-if="generatedFiles.length" class="generated-files">
            <h3>生成的文件：</h3>
            <div v-for="(file, index) in generatedFiles" :key="index" class="file-item">
              <div class="file-header">
                <span>{{ file.filename }}</span>
                <el-button type="primary" link @click="handleCopyCode(file.content)">复制代码</el-button>
              </div>
              <el-input
                type="textarea"
                v-model="file.content"
                :rows="10"
                readonly
              />
            </div>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 模板编辑对话框 -->
    <el-dialog
      v-model="templateDialog.visible"
      :title="templateDialog.type === 'add' ? '新增模板' : '编辑模板'"
      width="800px"
    >
      <el-form ref="templateFormRef" :model="templateForm" label-width="120px">
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="templateForm.name" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="templateForm.description" type="textarea" placeholder="请输入模板描述" />
        </el-form-item>
        <el-form-item label="变量定义">
          <div v-for="(variable, index) in templateForm.variables" :key="index" class="variable-item">
            <el-input v-model="variable.key" placeholder="变量名" style="width: 150px" />
            <el-input v-model="variable.label" placeholder="显示名称" style="width: 150px" />
            <el-select v-model="variable.type" placeholder="变量类型" style="width: 150px">
              <el-option label="文本" value="text" />
              <el-option label="数组" value="array" />
            </el-select>
            <el-button type="danger" link @click="removeVariable(index)">删除</el-button>
          </div>
          <el-button type="primary" link @click="addVariable">添加变量</el-button>
        </el-form-item>

        <!-- 数组类型变量的字段定义 -->
        <template v-for="(variable, variableIndex) in templateForm.variables" :key="variableIndex">
          <el-form-item v-if="variable.type === 'array'" :label="variable.label + '字段定义'">
            <div class="array-fields-container">
              <div v-for="(field, fieldIndex) in variable.fields || []" :key="fieldIndex" class="field-item">
                <el-input v-model="field.key" placeholder="字段名" style="width: 150px" />
                <el-input v-model="field.label" placeholder="显示名称" style="width: 150px" />
                <el-button type="danger" link @click="removeField(variableIndex, fieldIndex)">删除</el-button>
              </div>
              <el-button type="primary" link @click="addField(variableIndex)">添加字段</el-button>
            </div>
          </el-form-item>
        </template>

        <el-form-item label="子模板">
          <div v-for="(subTemplate, index) in templateForm.subTemplates" :key="index" class="sub-template-item">
            <el-input v-model="subTemplate.filename" placeholder="文件名模板" style="width: 200px" />
            <el-input
              type="textarea"
              v-model="subTemplate.content"
              placeholder="模板内容"
              :rows="5"
            />
            <el-button type="danger" link @click="removeSubTemplate(index)">删除</el-button>
          </div>
          <el-button type="primary" link @click="addSubTemplate">添加子模板</el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="templateDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveTemplate">确定</el-button>
      </template>
    </el-dialog>

    <!-- 导出模板对话框 -->
    <el-dialog
      v-model="exportDialog.visible"
      title="导出模板"
      width="800px"
    >
      <div class="export-container">
        <p class="export-tip">复制以下内容到 templates.js 文件中的 presetTemplates 数组中：</p>
        <el-input
          v-model="exportDialog.content"
          type="textarea"
          :rows="20"
          readonly
        />
        <div class="export-actions">
          <el-button type="primary" @click="handleCopyExport">复制内容</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import Cookies from "js-cookie"
import useUserStore from '@/store/modules/user'
import { ElMessage } from 'element-plus'
import { presetTemplates } from './templates'

const userStore = useUserStore()
const route = useRoute()
const router = useRouter()
const { proxy } = getCurrentInstance()

// 标签页切换
const activeTab = ref('template')

// 模板列表
const templateList = ref([...presetTemplates])

// 代码生成表单
const genFormRef = ref()
const genForm = reactive({
  templateId: '',
  variables: {}
})

// 当前选中的模板
const currentTemplate = computed(() => {
  return templateList.value.find(t => t.id === genForm.templateId)
})

// 生成的文件列表
const generatedFiles = ref([])

// 模板对话框
const templateDialog = reactive({
  visible: false,
  type: 'add' // 'add' 或 'edit'
})

// 模板表单
const templateFormRef = ref()
const templateForm = reactive({
  id: '',
  name: '',
  description: '',
  variables: [],
  subTemplates: []
})

// 导出对话框
const exportDialog = reactive({
  visible: false,
  content: ''
})

// 添加模板
const handleAddTemplate = () => {
  templateDialog.type = 'add'
  templateDialog.visible = true
  Object.assign(templateForm, {
    id: '',
    name: '',
    description: '',
    variables: [],
    subTemplates: []
  })
}

// 编辑模板
const handleEditTemplate = (row) => {
  templateDialog.type = 'edit'
  templateDialog.visible = true
  Object.assign(templateForm, JSON.parse(JSON.stringify(row)))
}

// 删除模板
const handleDeleteTemplate = (row) => {
  proxy.$modal.confirm('确认删除该模板吗？').then(() => {
    const index = templateList.value.findIndex(t => t.id === row.id)
    if (index !== -1) {
      templateList.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  })
}

// 添加变量
const addVariable = () => {
  templateForm.variables.push({
    key: '',
    label: '',
    type: 'text',
    fields: []
  })
}

// 删除变量
const removeVariable = (index) => {
  templateForm.variables.splice(index, 1)
}

// 添加子模板
const addSubTemplate = () => {
  templateForm.subTemplates.push({
    filename: '',
    content: ''
  })
}

// 删除子模板
const removeSubTemplate = (index) => {
  templateForm.subTemplates.splice(index, 1)
}

// 保存模板
const handleSaveTemplate = () => {
  if (templateDialog.type === 'add') {
    const newTemplate = {
      ...templateForm,
      id: Date.now().toString()
    }
    templateList.value.push(newTemplate)
  } else {
    const index = templateList.value.findIndex(t => t.id === templateForm.id)
    if (index !== -1) {
      templateList.value[index] = { ...templateForm }
    }
  }
  templateDialog.visible = false
  ElMessage.success('保存成功')
}

// 添加字段
const addField = (variableIndex) => {
  const variable = templateForm.variables[variableIndex]
  if (!variable.fields) {
    variable.fields = []
  }
  variable.fields.push({
    key: '',
    label: ''
  })
}

// 删除字段
const removeField = (variableIndex, fieldIndex) => {
  templateForm.variables[variableIndex].fields.splice(fieldIndex, 1)
}

// 添加数组项
const addArrayItem = (key, fields) => {
  if (!genForm.variables[key]) {
    genForm.variables[key] = []
  }
  // 创建新项时，为每个字段创建空值
  const newItem = {}
  fields.forEach(field => {
    newItem[field.key] = ''
  })
  genForm.variables[key].push(newItem)
}

// 删除数组项
const removeArrayItem = (key, index) => {
  genForm.variables[key].splice(index, 1)
}

// 生成代码
const handleGenerate = () => {
  if (!currentTemplate.value) return
  
  const files = currentTemplate.value.subTemplates.map(subTemplate => {
    // 处理文件名模板
    let filename = subTemplate.filename
    Object.entries(genForm.variables).forEach(([key, value]) => {
      const variable = currentTemplate.value.variables.find(v => v.key === key)
      // 如果是数组类型，转换为 JSON 字符串
      const replaceValue = variable?.type === 'array' ? JSON.stringify(value) : value
      filename = filename.replace(new RegExp(`\\{\\{\\$${key}\\}\\}`, 'g'), replaceValue || '')
    })
    
    // 处理内容模板
    let content = subTemplate.content
    
    // 处理所有变量
    const processVariables = (text, contextVariables = {}) => {
      // 递归处理模板
      const processTemplate = (template, context) => {
        let result = template
        
        // 处理条件判断块
        result = result.replace(
          /\{\{#if ([^}]+)\}\}([\s\S]*?)(?:\{\{#else\}\}([\s\S]*?))?\{\{\/if\}\}/g,
          (match, condition, ifContent, elseContent = '') => {
            // 解析条件表达式
            const evalCondition = (expr) => {
              // 替换变量引用，支持访问对象属性
              const processedExpr = expr.replace(/\$([a-zA-Z0-9_]+)(\.[\w.]+)?/g, (m, varName, prop = '') => {
                let value = context[varName] || genForm.variables[varName]
                
                // 处理属性访问
                if (prop) {
                  try {
                    value = prop.split('.').reduce((obj, key) => obj?.[key.slice(1)], value)
                  } catch (e) {
                    console.error('属性访问错误:', e)
                    return 'undefined'
                  }
                }
                
                if (typeof value === 'string') return `'${value}'`
                return JSON.stringify(value)
              })
              
              try {
                const safeEval = new Function('return ' + processedExpr)
                return safeEval()
              } catch (e) {
                console.error('条件表达式评估错误:', e)
                return false
              }
            }

            // 获取模板的缩进
            const lines = match.split('\n')
            const firstLine = lines[0]
            const indent = firstLine.match(/^\s*/)[0]
            
            // 评估条件并选择内容
            const selectedContent = evalCondition(condition) ? ifContent : elseContent
            
            // 递归处理选中的内容
            if (!selectedContent) return ''
            const processedContent = processTemplate(selectedContent, context)
            
            // 处理选中内容的缩进
            const contentLines = processedContent.split('\n')
            return contentLines
              .map((line, i) => i === 0 ? line : indent + line.trim())
              .join('\n')
          }
        )
        
        // 处理循环块
        result = result.replace(
          /\{\{#each \$([^}]+)\}\}([\s\S]*?)\{\{\/each\}\}/g,
          (match, arrayKey, template) => {
            const arrayValue = context[arrayKey] || genForm.variables[arrayKey]
            if (!Array.isArray(arrayValue)) return ''
            
            // 获取模板的缩进
            const lines = match.split('\n')
            const firstLine = lines[0]
            const indent = firstLine.match(/^\s*/)[0]
            
            // 移除首尾空行，并保持每行的缩进
            const cleanTemplate = lines
              .slice(1, -1)
              .map(line => line.slice(indent.length))
              .join('\n')
            
            return arrayValue.map((item, index) => {
              // 创建循环项的上下文变量
              const itemContext = {
                ...context,
                item,
                index,
                // 添加一些有用的循环变量
                first: index === 0,
                last: index === arrayValue.length - 1,
                count: arrayValue.length
              }
              
              // 递归处理模板内容
              let processedTemplate = processTemplate(cleanTemplate, itemContext)
              
              // 处理循环项中的变量
              Object.entries(item).forEach(([key, value]) => {
                processedTemplate = processedTemplate.replace(
                  new RegExp(`\\{\\{\\$${key}\\}\\}`, 'g'),
                  value || ''
                )
              })
              
              return indent + processedTemplate
            }).join('\n')
          }
        )
        
        // 处理普通变量
        Object.entries({ ...genForm.variables, ...context }).forEach(([key, value]) => {
          if (typeof value !== 'object') {
            result = result.replace(
              new RegExp(`\\{\\{\\$${key}\\}\\}`, 'g'),
              value || ''
            )
          }
        })
        
        return result
      }
      
      // 开始处理模板
      return processTemplate(text, contextVariables)
    }
    
    // 首先处理内容中的循环
    content = processVariables(content)
    
    return {
      filename,
      content
    }
  })
  
  generatedFiles.value = files
}

// 复制代码
const handleCopyCode = async (code) => {
  try {
    await navigator.clipboard.writeText(code)
    ElMessage.success('复制成功')
  } catch (err) {
    ElMessage.error('复制失败')
  }
}

// 处理导出模板
const handleExportTemplate = (template) => {
  // 创建一个新的对象，移除不需要的属性
  const exportTemplate = {
    ...template
  }
  
  // 格式化子模板内容
  const formatSubTemplates = (subTemplates) => {
    return subTemplates.map(subTemplate => {
      const content = subTemplate.content
        .replace(/`/g, '\\`') // 转义反引号
        .replace(/\${/g, '\\${') // 转义模板字符串插值
      
      return {
        filename: subTemplate.filename,
        content: `\`${content}\``
      }
    })
  }
  
  // 格式化对象为字符串
  const formatObject = (obj, level = 1) => {
    const indent = '  '.repeat(level)
    const entries = Object.entries(obj)
    
    return `{\n${entries.map(([key, value]) => {
      const formattedValue = formatValue(value, level + 1)
      return `${indent}  ${key}: ${formattedValue}`
    }).join(',\n')}\n${indent}}`
  }
  
  // 格式化数组
  const formatArray = (arr, level = 1) => {
    const indent = '  '.repeat(level)
    return `[\n${arr.map(item => {
      const formattedItem = formatValue(item, level + 1)
      return `${indent}  ${formattedItem}`
    }).join(',\n')}\n${indent}]`
  }
  
  // 格式化值
  const formatValue = (value, level) => {
    if (value === null || value === undefined) {
      return 'null'
    }
    if (typeof value === 'string') {
      if (value.startsWith('`')) {
        return value
      }
      return `'${value}'`
    }
    if (Array.isArray(value)) {
      return formatArray(value, level)
    }
    if (typeof value === 'object') {
      return formatObject(value, level)
    }
    return value
  }
  
  // 处理子模板
  exportTemplate.subTemplates = formatSubTemplates(exportTemplate.subTemplates)
  
  // 生成最终的格式化字符串
  const result = formatObject(exportTemplate)
  
  // 添加适当的缩进
  exportDialog.content = result
  exportDialog.visible = true
}

// 复制导出内容
const handleCopyExport = async () => {
  try {
    await navigator.clipboard.writeText(exportDialog.content)
    ElMessage.success('复制成功')
    exportDialog.visible = false
  } catch (err) {
    ElMessage.error('复制失败')
  }
}
</script>

<style lang='scss' scoped>
.app-container {
  padding: 20px;
  
  .template-container,
  .generation-container {
    margin-top: 20px;
  }
  
  .template-header {
    margin-bottom: 20px;
  }
  
  .variable-item,
  .sub-template-item {
    display: flex;
    gap: 10px;
    margin-bottom: 10px;
    align-items: flex-start;
    
    .el-input {
      margin-right: 10px;
    }
  }
  
  .generated-files {
    margin-top: 20px;
    
    .file-item {
      margin-bottom: 20px;
      
      .file-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;
      }
    }
  }
}

.array-items-container {
  .array-item {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 10px;
    margin-bottom: 10px;
    
    .field-item {
      display: flex;
      align-items: center;
      margin-bottom: 10px;
      
      .field-label {
        width: 100px;
        text-align: right;
        margin-right: 10px;
      }
    }
  }
}

.array-fields-container {
  .field-item {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 10px;
  }
}

.export-container {
  .export-tip {
    margin-bottom: 10px;
    color: #666;
  }

  .export-actions {
    margin-top: 10px;
    text-align: right;
  }
}
</style>
